import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

/// Flutter网络和数据示例
class NetworkDataExample extends StatefulWidget {
  const NetworkDataExample({super.key});

  @override
  State<NetworkDataExample> createState() => _NetworkDataExampleState();
}

class _NetworkDataExampleState extends State<NetworkDataExample> {
  bool _isLoading = false;
  String _result = '';
  List<Map<String, dynamic>> _users = [];

  // 模拟API请求
  Future<Map<String, dynamic>> _fetchUserData() async {
    await Future.delayed(const Duration(seconds: 2));
    return {'id': 1, 'name': '张三', 'email': 'zhangsan@example.com', 'age': 25};
  }

  // 真实API请求（JSONPlaceholder）
  Future<List<Map<String, dynamic>>> _fetchRealUsers() async {
    try {
      final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));

      if (response.statusCode == 200) {
        final List<dynamic> data = json.decode(response.body);
        return data.cast<Map<String, dynamic>>();
      } else {
        throw Exception('请求失败: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('网络错误: $e');
    }
  }

  void _handleSimpleRequest() async {
    setState(() {
      _isLoading = true;
      _result = '';
    });

    try {
      final data = await _fetchUserData();
      setState(() {
        _result =
            '''
请求成功！

ID: ${data['id']}
姓名: ${data['name']}
邮箱: ${data['email']}
年龄: ${data['age']}
        ''';
      });
    } catch (e) {
      setState(() {
        _result = '请求失败: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _handleRealRequest() async {
    setState(() {
      _isLoading = true;
      _users = [];
      _result = '';
    });

    try {
      final users = await _fetchRealUsers();
      setState(() {
        _users = users;
        _result = '成功获取 ${users.length} 个用户';
      });
    } catch (e) {
      setState(() {
        _result = '请求失败: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter 网络和数据'), backgroundColor: Theme.of(context).colorScheme.inversePrimary),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 说明卡片
            Card(
              color: Colors.blue.shade50,
              child: const Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('🌐 网络请求概述', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    SizedBox(height: 8),
                    Text(
                      'Flutter网络请求方式：\n'
                      '• http包：简单的HTTP请求\n'
                      '• dio包：功能更强大（后面综合App使用）\n'
                      '• FutureBuilder：处理异步数据\n'
                      '• JSON解析：数据序列化',
                      style: TextStyle(fontSize: 14),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // HTTP基础请求
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('HTTP请求基础', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 12),
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
                      child: const Text('''import 'package:http/http.dart' as http;
import 'dart:convert';

// GET请求
Future<Map<String, dynamic>> fetchData() async {
  final response = await http.get(
    Uri.parse('https://api.example.com/data'),
  );
  
  if (response.statusCode == 200) {
    return json.decode(response.body);
  } else {
    throw Exception('请求失败');
  }
}

// POST请求
Future<void> postData(Map<String, dynamic> data) async {
  final response = await http.post(
    Uri.parse('https://api.example.com/data'),
    headers: {'Content-Type': 'application/json'},
    body: json.encode(data),
  );
}''', style: TextStyle(fontFamily: 'monospace', fontSize: 11)),
                    ),
                    const SizedBox(height: 16),
                    FilledButton.icon(
                      onPressed: _isLoading ? null : _handleSimpleRequest,
                      icon: const Icon(Icons.download),
                      label: const Text('发起模拟请求'),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 真实API请求
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('真实API请求（JSONPlaceholder）', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 12),
                    FilledButton.icon(
                      onPressed: _isLoading ? null : _handleRealRequest,
                      icon: const Icon(Icons.cloud_download),
                      label: const Text('获取用户列表'),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 加载指示器
            if (_isLoading)
              const Card(
                child: Padding(
                  padding: EdgeInsets.all(32),
                  child: Center(child: Column(children: [CircularProgressIndicator(), SizedBox(height: 16), Text('加载中...')])),
                ),
              ),

            // 结果显示
            if (_result.isNotEmpty)
              Card(
                color: Colors.green.shade50,
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Row(
                        children: [
                          Icon(Icons.check_circle, color: Colors.green),
                          SizedBox(width: 8),
                          Text('请求结果', style: TextStyle(fontWeight: FontWeight.bold)),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Text(_result),
                    ],
                  ),
                ),
              ),

            // 用户列表
            if (_users.isNotEmpty)
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text('用户列表', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                      const SizedBox(height: 12),
                      ..._users.take(5).map((user) {
                        return ListTile(
                          leading: CircleAvatar(child: Text(user['id'].toString())),
                          title: Text(user['name']),
                          subtitle: Text(user['email']),
                        );
                      }),
                    ],
                  ),
                ),
              ),

            const SizedBox(height: 16),

            // FutureBuilder示例
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('FutureBuilder（推荐方式）', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 12),
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
                      child: const Text('''FutureBuilder<Map<String, dynamic>>(
  future: fetchData(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text('数据: \${snapshot.data}');
    } else if (snapshot.hasError) {
      return Text('错误: \${snapshot.error}');
    }
    return CircularProgressIndicator();
  },
)''', style: TextStyle(fontFamily: 'monospace', fontSize: 12)),
                    ),
                    const SizedBox(height: 12),
                    FutureBuilder<Map<String, dynamic>>(
                      future: _fetchUserData(),
                      builder: (context, snapshot) {
                        if (snapshot.connectionState == ConnectionState.waiting) {
                          return const Center(
                            child: Padding(padding: EdgeInsets.all(16), child: CircularProgressIndicator()),
                          );
                        }

                        if (snapshot.hasError) {
                          return Container(
                            padding: const EdgeInsets.all(12),
                            decoration: BoxDecoration(color: Colors.red.shade50, borderRadius: BorderRadius.circular(8)),
                            child: Text('错误: ${snapshot.error}'),
                          );
                        }

                        if (snapshot.hasData) {
                          final data = snapshot.data!;
                          return Container(
                            padding: const EdgeInsets.all(12),
                            decoration: BoxDecoration(color: Colors.blue.shade50, borderRadius: BorderRadius.circular(8)),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [Text('姓名: ${data['name']}'), Text('邮箱: ${data['email']}'), Text('年龄: ${data['age']}')],
                            ),
                          );
                        }

                        return const SizedBox();
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // JSON处理
            Card(
              color: Colors.purple.shade50,
              child: const Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('JSON处理技巧：', style: TextStyle(fontWeight: FontWeight.bold)),
                    SizedBox(height: 8),
                    Text('• json.decode() - JSON字符串转Map/List'),
                    Text('• json.encode() - Map/List转JSON字符串'),
                    Text('• 定义Model类处理复杂数据'),
                    Text('• 使用json_serializable自动生成代码'),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
